package excel

import (
	"github.com/xuri/excelize/v2"
	"testCode/excel_export/internal/excel/factory"
)

type DataProvider interface {
	GetHeaders() []string     // 获取表头
	GetRows() [][]interface{} // 获取行数据
	GetExportType() string    // 获取导出类型标识
}

type StyleStrategy interface {
	ApplyHeaderStyle(f *excelize.File, sheet string, headers []string) error   // 表头样式
	ApplyBodyStyle(f *excelize.File, sheet string, data [][]interface{}) error // 单元格样式
}

type Exporter struct {
	dataProvider  DataProvider
	styleStrategy StyleStrategy
}

func NewExporter(dp DataProvider) *Exporter {
	return &Exporter{
		dataProvider:  dp,
		styleStrategy: factory.NewStyleStrategy(dp.GetExportType()),
	}
}

func (e *Exporter) Export() (*excelize.File, error) {
	f := excelize.NewFile()
	sheet := "Sheet 1"

	// 写入数据
	headers := e.dataProvider.GetHeaders()
	for i, h := range headers {
		cell, _ := excelize.CoordinatesToCellName(i+1, 1)
		f.SetCellValue(sheet, cell, h)
	}

	rows := e.dataProvider.GetRows()
	for rIdx, row := range rows {
		for cIdx, val := range row {
			cell, _ := excelize.CoordinatesToCellName(cIdx+1, rIdx+2)
			f.SetCellValue(sheet, cell, val)
		}
	}

	// 应用样式
	if err := e.styleStrategy.ApplyHeaderStyle(f, sheet, headers); err != nil {
		return nil, err
	}
	if err := e.styleStrategy.ApplyBodyStyle(f, sheet, rows); err != nil {
		return nil, err
	}

	return f, nil
}
